package com.fly.json;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

import org.apache.commons.io.IOUtils;
import org.junit.jupiter.api.Test;
import org.springframework.core.io.ClassPathResource;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fly.core.utils.JsonBeanUtils;
import com.fly.demo.entity.BlogData;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ParseJsonIgnoreError
{
    /**
     * thread-safe
     */
    ObjectMapper mapper = new ObjectMapper();
    
    /**
     * 解析为实体
     * 
     * @throws IOException
     */
    @Test
    public void testToEntity1()
        throws IOException
    {
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) // 无法识别字段是否快速失败
            .readValue(getJsonData(), BlogData.class)
            .getData()
            .getList()
            .stream()
            .forEach(article -> log.info("{} ", article));
    }
    
    /**
     * 解析为实体
     * 
     * @throws IOException
     */
    @Test
    public void testToEntity2()
        throws IOException
    {
        JsonBeanUtils.jsonToBean(getJsonData(), BlogData.class, true) // BlogData
            .getData()
            .getList()
            .stream()
            .forEach(article -> log.info("{} ", article));
    }
    
    /**
     * 获取jsonData
     * 
     * @return
     * @throws IOException
     */
    private String getJsonData()
        throws IOException
    {
        try (InputStream input = new ClassPathResource("data.json").getInputStream())
        {
            return IOUtils.toString(input, StandardCharsets.UTF_8);
        }
    }
}
